package gupao.concurrency.api.sample;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

@Slf4j
public class ApiHandler implements InvocationHandler {
    private Object object;
    public ApiHandler(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        Exception exp = null;
        long st = System.currentTimeMillis();
        try {
            result = method.invoke(object,args);
        } catch (Exception e) {
            Throwable cause = e.getCause();
            log.info("cause: {}", cause.getMessage());
            result = null;
            exp = e;
        }
        long times = System.currentTimeMillis() - st;
        if(exp == null){
            ApiInvokeInfo info = ApiInvokeInfo.createSuccessInfo(method.getName(), times);
            TBApiContextCache.get().addApiInvokeInfo(info);
        }else{
            ApiInvokeInfo info = ApiInvokeInfo.createErrorInfo(method.getName(), times, exp);
            TBApiContextCache.get().addApiInvokeInfo(info);
        }
        return result;
    }
}
